package com.supcon.tea.work.questionnaire.controller;

import com.alibaba.fastjson.JSONObject;
import com.supcon.tea.common.Recode;
import com.supcon.tea.work.questionnaire.domain.dto.AnswerDTO;
import com.supcon.tea.work.questionnaire.domain.dto.QuestionnaireDTO;
import com.supcon.tea.work.questionnaire.service.QuestionnaireService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by zhengjian1 on 2017/7/21.
 */
@Controller
@RequestMapping(value="/questionnaire")
public class QuestionnaireController {
    @Autowired
    private QuestionnaireService questionnaireService;

    @RequestMapping(value= "",method = RequestMethod.GET)
    public String index(Model model){
        model.addAttribute("name", "world");
        return "/index";
    }
    @RequestMapping(value= "/type",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getQuestions(
            @RequestParam(value = "userId", required = false)String userId,
            @RequestParam(value = "type",required = false, defaultValue = "2")  Integer type,
            @RequestParam(value = "sex", required = false, defaultValue = "2")Integer sex){
        JSONObject result = new JSONObject();
        System.out.println(sex);
        QuestionnaireDTO questionnaireDTO = questionnaireService.getQuestionnaire(userId,type,sex);
        if(questionnaireDTO!=null){
            result.put("recode",Recode.SUCCESS);
            result.put("msg","成功");
            result.put("data",questionnaireDTO);
        }else{
            result.put("recode", Recode.ERROR);
            result.put("msg","未查到相关数据");
        }
        return new ResponseEntity<JSONObject>(result, HttpStatus.OK);
    }
    @RequestMapping(value= "/answers",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> postAnswer(@RequestBody @Valid AnswerDTO answerDTO,BindingResult r){
        JSONObject result = new JSONObject();
        if(r.hasErrors()){
            result.put("recode",Recode.SUCCESS);
            result.put("msg",r.getAllErrors());
            return new ResponseEntity<JSONObject>(result, HttpStatus.OK);
        }
        result = this.questionnaireService.fixAnswer(answerDTO);
        return new ResponseEntity<JSONObject>(result, HttpStatus.OK);
    }

}
